namespace RAG.Application.Dtos;

/// <summary>
/// 向量DTO，用于业务层封装
/// </summary>
public class VectorDto
{
    public float[] Values { get; set; } = null!;
    
    public VectorDto(float[] values)
    {
        Values = values;
    }
    
    public VectorDto()
    {
    }
    
    /// <summary>
    /// 计算与另一个向量的余弦相似度
    /// </summary>
    public float CosineSimilarity(VectorDto other)
    {
        if (Values.Length != other.Values.Length)
            throw new ArgumentException("向量维度必须相同");
            
        float dotProduct = 0;
        float normA = 0;
        float normB = 0;
        
        for (int i = 0; i < Values.Length; i++)
        {
            dotProduct += Values[i] * other.Values[i];
            normA += Values[i] * Values[i];
            normB += other.Values[i] * other.Values[i];
        }
        
        normA = (float)Math.Sqrt(normA);
        normB = (float)Math.Sqrt(normB);
        
        if (normA == 0 || normB == 0)
            return 0;
            
        return dotProduct / (normA * normB);
    }
    
    /// <summary>
    /// 计算欧几里得距离
    /// </summary>
    public float EuclideanDistance(VectorDto other)
    {
        if (Values.Length != other.Values.Length)
            throw new ArgumentException("向量维度必须相同");
            
        float sum = 0;
        for (int i = 0; i < Values.Length; i++)
        {
            float diff = Values[i] - other.Values[i];
            sum += diff * diff;
        }
        
        return (float)Math.Sqrt(sum);
    }
    
    /// <summary>
    /// 从float[]创建VectorDto
    /// </summary>
    public static VectorDto FromArray(float[] values)
    {
        return new VectorDto(values);
    }
    
    /// <summary>
    /// 转换为float[]
    /// </summary>
    public float[] ToArray()
    {
        return Values;
    }
} 